import request from '@/utils/request'

/**
 * 发送聊天消息
 * @param {string} message - 用户消息
 * @param {string} sessionId - 会话ID
 * @returns {Promise} 包含AI回复的Promise
 */
export const sendChatMessage = (message, sessionId) => {
  return request({
    url: '/chat/completion',
    params: {
      prompt: message,
      chat_session_id: sessionId,
      parent_message_id: ''
    }
  })
}

/**
 * 获取会话历史
 * @returns {Promise} 包含会话历史的Promise
 */
export const getChatHistory = sessionId => {
  return request({
    url: '/chat/sessions',
    params: {
      chat_session_id: sessionId
    }
  })
}

// 发送对话
export function chatCompletions (stream, messages) {
  return fetchRequest('/compatible-mode/v1/chat/completions', {
    method: 'POST',
    body: JSON.stringify({
      model: 'deepseek-v3',
      messages: messages,
      stream: true,
      stream_options: {
        include_usage: true
      }
    }),
    signal: stream
  })
}

export default function fetchRequest (url, options) {
  const baseURL = 'https://dashscope.aliyuncs.com'
  const headers = {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${process.env.VUE_APP_MODEL_BAILIAN_AK}`
  }
  options.headers = {
    ...headers,
    ...options.headers
  }
  return fetch(baseURL + url, options)
}
